#include "voiceupload.h"
#include "appchat/accountmanager.h"
#include "account/accountuser.h"
#include <json.h>

namespace VoiceUpload {

VoiceUpload* VoiceUpload::m_instance = 0;

VoiceUpload* VoiceUpload::instance(QObject *parent)
{
    if (!m_instance) {
        m_instance = new VoiceUpload(parent);
    }
    return m_instance;
}

VoiceUpload::VoiceUpload(QObject *parent) :
    QObject(parent)
{
    http = new QNetworkAccessManager(this);
}

void VoiceUpload::upload()
{
    if(filename() == "")
        return;
    QFileInfo finfo(filename());
    int userId = AccountManager::instance()->getUserId();
    QString numFolder = QVariant(userId).toString();

    QNetworkRequest r(QUrl("http://upload-voice.cloud.me.zing.vn/up/" + numFolder));
    QString bound="---------------------------723690991551375881941828858";
    QByteArray data(QString("--"+bound+"\r\n").toUtf8());
    data += "Content-Disposition: form-data; name=\"action\"\r\n\r\n";
    data += "\r\n";
    data += QString("--" + bound + "\r\n").toUtf8();
    data += "Content-Disposition: form-data; name=\"file\"; filename=\""+finfo.fileName()+"\"\r\n";

    QString format = finfo.suffix().toLower();
    format = "basic";
    data += "Content-Type: audio/"+ format +"\r\n\r\n";

    QFile file(finfo.absoluteFilePath());
    file.open(QIODevice::ReadOnly);
    data += file.readAll();
    data += "\r\n";
    data += QString("--" + bound + "\r\n").toUtf8();
    data += QString("--" + bound + "\r\n").toUtf8();
    data += "Content-Disposition: form-data; name=\"desc\"\r\n\r\n";
    data += "\r\n";
    r.setRawHeader(QString("Accept-Encoding").toUtf8(), QString("gzip,deflate").toUtf8());
    r.setRawHeader(QString("Content-Type").toUtf8(),QString("multipart/form-data; boundary=" + bound).toUtf8());
    r.setRawHeader(QString("Content-Lengt").toUtf8(), QString::number(data.length()).toUtf8());

    reps.push_back(http->post(r,data));
    connect(reps.at(reps.size()-1),SIGNAL(finished()),this,SLOT(onUpload()));
}

void VoiceUpload::onUpload()
{
    for(int i=0;i<reps.size();i++){
        if(reps[i]->isFinished()){
            QString message=reps[i]->readAll();

            parserVoice(message.toUtf8());
            emit setVoice();
        }
    }

    reps.clear();
}

void VoiceUpload::parserVoice(QByteArray message)
{
    qDebug() << "Parse Voice:";
    qDebug() << message;
    JsonReader reader;
    QTextStream stream(message);
    QVariant variant;
    if (!reader.read(stream, variant))
        return;
    if (variant.type() != QVariant::List)
        return;

    QVariantList List = variant.toList();

    foreach (QVariant item, List) {
        if (item.type() != QVariant::Map) {
            return;
        }

        QVariantMap map = item.toMap();
        if (!map.contains("error_code")) {
            return;
        }

        QVariant varErrorCode = map.value("error_code");
        if(varErrorCode.type() != QVariant::Int){
            return;
        }

        if (!map.contains("error_message")) {
            return;
        }

        if (!map.contains("id")) {
            return;
        }
        QVariant idVoice = map.value("id");
        if (idVoice.type() != QVariant::Int) {
            return;
        }

        if (!map.contains("url")) {
            return;
        }
        QVariant urlVoice = map.value("url");
        if (urlVoice.type() != QVariant::String) {
            return;
        }
        QString url =  urlVoice.toString();
        emit sendVoiceUrl(url);

    }
}

}
